package cn.bugio.note.controller.content;

import cn.bugio.note.common.domain.messaging.UserAndBonusMsgDTO;
import cn.bugio.note.common.vo.ServerResponse;
import cn.bugio.note.rocketmq.MySource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Random;

/**
 * @author Vincent Vic
 * @version 1.0
 * @Description
 * @since 2021/2/16
 */

@RestController
@RequestMapping("/test/")
@Slf4j
public class TestController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("{id}")
    @ResponseBody
    public String findById(@PathVariable Integer id){
        log.info("请求id: {}",id);

        String forObject = restTemplate.getForObject("http://user-center/users/{id}", String.class, id);
        log.info("result -> {}",forObject);
        return forObject;
    }

    @GetMapping("token/{id}")
    @ResponseBody
    public ResponseEntity<String> tokenFindById(@PathVariable Integer id){
        log.info("请求id: {}",id);
        //1.从header里面获取token
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = attributes.getRequest();

        String token = request.getHeader("x-token");
        //设置访问的Entity
        HttpHeaders headers = new HttpHeaders();
        headers.add("x-token",token);
        HttpEntity entity = new HttpEntity<>(new HashMap<>(), headers);
        return restTemplate.exchange(
                "http://user-center/users/{id}",
                HttpMethod.GET,
                entity,
                String.class,
                id
        );

    }

    @Autowired
    private MySource mySource;

    @GetMapping("stream")
    @ResponseBody
    public ServerResponse testStream(){
        log.info("发送消息");
        // <2>创建 Message
        UserAndBonusMsgDTO message = UserAndBonusMsgDTO.builder().userId(1).bonus(50).build();
        // <3>创建 Spring Message 对象
        Message<UserAndBonusMsgDTO> springMessage = MessageBuilder.withPayload(message)
                .build();
        // <4>发送消息
        boolean send = mySource.erbadagangOutput().send(springMessage);

        return ServerResponse.success(send);
    }
}
